<template>
	<view>
		<cu-custom bgColor="bg-gradual-pink" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">样品出库登记</block>
		</cu-custom>
		<!-- <form @submit="submitForm"> -->
			<!-- 日期 -->
			<view class="cu-form-group">
				<view class="title">出库日期</view>
				<picker mode="date" :value="formData.chukuDate" @change="DateChange">
					<view class="picker">
						{{formData.chukuDate}}
					</view>
				</picker>
			</view>
			<picker-pop
				title="采样人"
				url="/pages/component/list2pop?dataKey=employList"
				:text="formData.employName"
				@change="changeEmploy"
			>
			</picker-pop>
			<picker-pop
				title="客户"
				url="/pages/component/list2pop?dataKey=clientList"
				:text="formData.clientName"
				@change="changeClient"
			>
			</picker-pop>
			<view class="cu-form-group">
				<view class="title">出库原因</view>
				<input v-model="formData.reason" placeholder="出库原因"></input>
			</view>

			<!-- 产品明细 批号输入，物料在弹窗中选择或者扫描-->
			<view name='mingxi' v-for="(mingxi,index) in formData.Products" :key="index">
				<view class="cu-bar solid-bottom margin-top" style="background-color: #dddddd" >
					<view class="action">
						<text class="cuIcon-titles text-orange"></text> 明细{{index+1}}（可动态增删）
					</view>
					<view class="action" @click="removeMingxi(index)">
						<text class="cuIcon-roundclose text-xs text-blue"></text>删除
					</view>
				</view>
				<view class="cu-form-group">
					<view class="title">产品编号</view>
					<input name="code" @confirm="searchSample" :data-index="index" confirm-type="search" v-model="mingxi.code" placeholder="完整产品编号"></input>
					<button class='cu-btn bg-blue shadow cuIcon-scan' :data-index="index" @tap="scanCode"></button>
				</view>
				<!-- <view class="cu-form-group">
					<view class="title">产品编号</view>
					<input :disabled="true" v-model="mingxi.proCode"></input>
				</view> -->
				<view class="cu-form-group">
					<view class="title">产品名称</view>
					<input :disabled="true" v-model="mingxi.proName"></input>
				</view>
				<view class="cu-form-group">
					<view class="title">花型颜色</view>
					<input :disabled="true" v-model="mingxi.proDesc"></input>
				</view>
				<view class="cu-form-group">
					<view class="title">样品类型</view>
					<input :disabled="true" v-model="mingxi.type"></input>
				</view>
				<view class="cu-form-group">
					<view class="title">格型</view>
					<input :disabled="true" v-model="mingxi.gexing"></input>
				</view>
				<view class="cu-form-group">
					<view class="title">组织</view>
					<input :disabled="true" v-model="mingxi.zuzhi"></input>
				</view>
				<!-- <view class="cu-form-group">
					<view class="title">弹力</view>
					<input :disabled="true" v-model="mingxi.tanli"></input>
				</view> -->
				<view class="cu-form-group">
					<view class="title">后整理</view>
					<input :disabled="true" v-model="mingxi.hzl"></input>
				</view>
				<view class="cu-form-group">
					<view class="title">库位</view>
					<input :disabled="true" v-model="mingxi.kuweiName"></input>
				</view>
				<view class="cu-form-group">
					<view class="title">库存</view>
					<input :disabled="true" v-model="mingxi.kucun"></input>
				</view>
				<view class="cu-form-group">
					<view class="title">出库数量</view>
					<input @input="inputCnt" :value="mingxi.cnt" :data-index="index" placeholder="输入数量"></input>
				</view>
				<view class="cu-form-group">
					<view class="title">单价</view>
					<input v-model="mingxi.price" placeholder="输入单价"></input>
				</view>
				<view class="cu-form-group">
					<view class="title">其他说明</view>
					<input v-model="mingxi.memoView" placeholder="输入其他说明"></input>
				</view>
			</view>

			<view v-if="pageType!='detial'" class="cu-form-group margin-top" @click="appendMingxi">
				<view class="flex-sub text-center">
					<view class="padding text-blue">
						<text class="cuIcon-add text-xs"></text>新增明细
					</view>
				</view>
			</view>

			<!-- 提交按钮 -->
			<view v-if="pageType!='detial'" class="uni-btn-v uni-common-mt uni-form-button padding-xl">
				<button class="btn-submit block bg-blue cu-btn lg" @tap="submitForm" formType="submit" :disabled="disabledSubmit" type="primary">
					<text v-if="disabledSubmit" class="cuIcon-loading2 cuIconfont-spin"></text> 提交
				</button>
				<!-- <button type="default" class="cu-btn block bg-white lg margin-tb-sm" formType="reset">重置</button> -->
			</view>
		<!-- </form> -->
	</view>
</template>

<script>
	import pickerPop from "@/components/picker-pop.vue"
	import formatData from '@/common/formData.js';
	import autocomplete from '@/components/autocomplete.vue';
	export default {
		components: {pickerPop,autocomplete},
		data() {
			return {
				formData:{
					chukuDate: '',
					kuwei: 'reason',
					employId:0,
					clientId:0,
					Products : []
				},
				scanText:'',
				mdselectUrl:'../../pages/fabric/Select/madanSelect',
				modalName: null,
				pageType:'',
				disabledSubmit:false,
			}
		},
		watch:{
			// formData:{
			// 	deep:true
			// }
		},
		onShow() {
			// console.log('show')
			// this.formData.Products.splice(0,1);
		},
		onLoad(query){
			let self = this;
			this.pageType = query.type;
			this.formData.chukuDate = formatData.dateToday();
			// console.log(this.chukuDate);
			// #ifdef APP-PLUS
		// 	let main = plus.android.runtimeMainActivity();//获取activity
		// 	let context = plus.android.importClass('android.content.Context'); //上下文
		// 	let receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver',{onReceive : doReceive });
		// 	let IntentFilter = plus.android.importClass('android.content.IntentFilter');
		// 	let filter = new IntentFilter();
		// 	filter.addAction("com.qs.scancode");//监听扫描
		// 	main.registerReceiver(receiver,filter);//注册监听

		// 	function doReceive(context, intent) {
		// 		plus.android.importClass(intent);//通过intent实例引入intent类，方便以后的‘.’操作
		// 		let result = intent.getStringExtra("code");
		// 		self.scanText=result
		// 		self.createMingxi();
		// 	}
			// #endif
			/* 修改模式 */
			if(query.id){
				var params = {
					method:'sample.chuku.detial',
					id:query.id||'',
				};
				formatData.set(params);
				uni.request({
					url: formatData.httpUrl(), //仅为示例，并非真实接口地址。
					data:params,
					success: (res) => {
						var result = res.data.data;
						if(result)self.formData = result;
					},
					fail: (res) => {

					}
				});
			}
		},

		methods: {
			//删除产品明细
			removeMingxi(index) {
				if(index < 0) return false;
				if(index > this.formData.Products.length-1) return false;
				var _rowDetail = this.formData.Products[index];

				//判断是否有id
				if(_rowDetail.id){
					var params = {
						method:'sample.chuku.detial.remove',
						sid : _rowDetail.id || ''
					};
					formatData.set(params);
					uni.request({
						url: formatData.httpUrl(), //仅为示例，并非真实接口地址。
						data:params,
						success: (res) => {
							if(res.data.data.success){
								this.formData.Products.splice(index,1);
							}else{
								uni.showToast({title:result.msg || '删除服务端失败', icon:"none"});
							}
						}
					});
				}else{
					this.formData.Products.splice(index,1);
				}

			},
			appendMingxi() {
				this.formData.Products.push({});
			},
			// createMingxi: async function () {
			// 	var len = this.formData.Products.length;
			// 	var currIndex = len;

			// 	/* 条码扫描加载明细 */
			// 	var params = {
			// 		method:'uni.fabric.chukuSearch',
			// 		code : this.scanText || ''
			// 	};
			// 	formatData.set(params);
			// 	let err,res;
			// 	[err,res] = await uni.request({
			// 		url: formatData.httpUrl(),
			// 		data: params
			// 	});
			// 	var newArr = res.data.data;
			// 	if(res.statusCode==200){
			// 		this.formData.Products.push(newArr.data);
			// 	}
			// 	let url = '../../pages/fabric/Select/madanSelect';
			// 	let md_params = {
			// 		proId: this.formData.Products[currIndex].productId,
			// 		mJson:newArr.data.madanJson
			// 	}
			// 	let result =this.$navTo.formate(url,md_params);
			// 	this.formData.Products[currIndex].mdselectUrl = result;
			// },
			//码单发生变化
			// changeMadan(res){
			// 	let madanJson = res.data;
			// 	let index = res.index;
			// 	let proId  = this.formData.Products[index].productId;
			// 	this.formData.Products[index].madan2 = madanJson;
			// 	this.formData.Products[index].madanJson = madanJson;
			// 	let url = '../../pages/fabric/Select/madanSelect';
			// 	let change_params = {
			// 		mJson:madanJson,
			// 		proId: proId,
			// 		proId2: 3,
			// 	}
			// 	let _res =this.$navTo.formate(url,change_params);
			// 	this.formData.Products[index].mdselectUrl = _res;
			// 	this.$forceUpdate();
			// },
			submitForm() {
				this.disabledSubmit = true;
				var that = this;

				console.log('表单数据，',this.formData);
				var params = {
					method:'sample.chuku.update',
					formData:JSON.stringify(this.formData)
				};
				formatData.set(params);
				uni.request({
					url: formatData.httpUrl(), //仅为示例，并非真实接口地址。
					data:params,
					method:'POST',
					header: {
					  'content-type': 'application/x-www-form-urlencoded'
					},
					success: (res) => {
						var result = res.data.data;
						console.log('result，',res);
						//如果后台保存成功
						if(result.success){
							uni.showLoading({
							    title: result.msg || '操作成功',
								mask:true,
							});
							setTimeout(function(){
								uni.hideLoading();
								uni.navigateBack({
									delta: 1
								});
							},500);
						}else{
							uni.showToast({title:result.msg||(res.data.res||'提交状态未知'), icon:"none"});
							that.disabledSubmit = false;
						}
					},
					complete: (res) => {
						setTimeout(function(){
							that.disabledSubmit = false;
						},200)
					}
				});
			},
			//日期选择改变，
			//todo ，后期改为自定义组件，使得代码调用更方便
			DateChange(e) {
				this.formData.chukuDate = e.detail.value
			},
			changeEmploy(res){
				console.log(res)
				this.formData.employId = res.data.id
			},
			changeClient(res){
				this.formData.clientId = res.data.cid
			},
			scanCode(e){
				// console.log('scanCode tap =>',e);
				var _this = this;
				var _index = e.target.dataset.index ;
				uni.scanCode({
				    success: function (res) {
				        // console.log('条码类型：' + res.scanType);
				        // console.log('条码内容：' + res.result);
						var code = res.result;
						_this.toPageKucun(_index ,code);
				    }
				});
			},
			inputCnt(e){
				var _this = this;
				var _val = e.detail.value || 0;
				var _index = e.target.dataset.index ;
				var _cnt = 0;
				var o = this.formData.Products[_index];
				var _kucun = (parseFloat(o.kucun) || 0) + (parseFloat(o.oldCnt) || 0);
				// console.log('kucun =>',_kucun,'cnt',_val);
				if(_val > _kucun){
					_cnt = 0;
					uni.showToast({title:'出库数量不能大于库存数量', icon:"none"});
				}else{
					_cnt = _val;
				}

				o.cnt = _cnt;
				setTimeout(() => {
					_this.$set(_this.formData.Products ,_index ,o);
				}, 0)
				return _cnt;
			},
			searchSample(e){
				// console.log('@confirm input to page kucun by code =>',e);
				var _this = this;
				var _val = e.detail.value || '';
				var _index = e.target.dataset.index ;

				if(_val == ''){
					uni.showToast({title:'无条码信息', icon:"none"});
					return false;
				}
				this.toPageKucun(_index ,_val);

			},
			toPageKucun(index ,code){
				var _this = this;
				var _index = index;
				//定义监听事件，跳转到库存页面，默认带上条码查找条码信息
				_this.$eventHub.$on('eventSelect', function (data) {
					console.log('data-data:',data);
					var _data = data.data;
					//先注销监听事件
					_this.$eventHub.$off('eventSelect');
					var _new = _data ? {
						code:code,
						proCode:_data.proCode || '',
						proDesc:_data.proDesc || '',
						kindName:_data.kindName || '',
						kuweiId:_data.kuweiId || 0,
						kuweiName:_data.kuweiName || '',
						kucun:_data.cnt || '',
						proName:_data.proName || '',
						productId:_data.productId || 0,
						type:_data.type || '',
						gexing:_data.gexing || '',
						hzl:_data.hzl || '',
						zuzhi:_data.zuzhi || '',
						// tanli:_data.tanli || '',
					} : {};
					_this.$set(_this.formData.Products ,_index ,_new);
					// _this.formData.Products[_index] = _new;
				});

				uni.navigateTo({
					url: "/pages/component/list2product?dataKey=kucunList&code="+code
				})
			}
		}
	}
</script>

<style>
	input {
		text-align: right;
	}
	/* webkit solution */
	::-webkit-input-placeholder { text-align:right; }
	/* mozilla solution */
	input:-moz-placeholder { text-align:right; }
</style>

